#!/usr/bin/env bash
set -ex

for fs in /tmp /dev/shm; do
    # only remount if it is currently mounted, AND if we know how to mount it again
    do_unmount=0
    do_mount=0
    if findmnt "$fs" >/dev/null && grep -q "$fs " /etc/fstab; then
        do_unmount=1
        do_mount=1
    fi

    # unmount
    if [ "$do_unmount" = 1 ]; then
        if ! umount "$fs" 2>/dev/null; then
            logger -s -t slurm "INFO: Failed to unmount $fs. Skipping remount and deleting files instead."
            do_mount=0
        fi
    fi

    # cleanup underlying FS (might be a noop)
    find "$fs" -mindepth 1 -delete

    # remount
    if [ "$do_mount" = 1 ]; then
        mount "$fs"
    fi
done
